﻿using System;
using System.Collections.Generic;
using System.Linq;
using JQuery.WebKit.Common.Extenstions;

namespace JQuery.WebKit
{
    public class JComboItemCollection : List<JComboItem>
    {
        private JCombo _parent;

        public JComboItemCollection(JCombo parent)
        {
            _parent = parent;
        }

        public void AddFromList(IEnumerable<object> itemList, string textColumn, string valueColumn)
        {
            this.Clear();
            foreach (object item in itemList)
            {
                string val = Convert.ToString(item.GetPropertyValue(valueColumn));
                string text = Convert.ToString(item.GetPropertyValue(textColumn));
                if (string.IsNullOrWhiteSpace(val) || string.IsNullOrWhiteSpace(val))
                {
                    continue;
                }
                this.Add(new JComboItem(_parent, text, val));
            }
            EnsureSelection();
        }

        protected internal void EnsureSelection()
        {
            if (this.Count > 0)
            {
                bool hasSelected = false;
                bool checkAllItem = _parent.FirstItemChecksAll.HasValue && _parent.FirstItemChecksAll.Value;
                if (!checkAllItem && this.Count(item => item.Selected) == 0 && (_parent.Required.HasValue && _parent.Required.Value))
                {
                    this[0].Selected = true;
                    _parent.Value = this[0].Value;
                    hasSelected = true;
                }
                
                if (!_parent.MultiSelect && _parent.Page != null && !_parent.Page.IsPostBack && !_parent.Page.IsRefresh)
                {
                    //ensure only one item is selected
                    int i = 0;
                    while (i < this.Count)
                    {
                        if (hasSelected)
                        {
                            this[i].Selected = false;
                        }
                        else if (this[i].Selected)
                        {
                            hasSelected = true;
                            _parent.Value = this[i].Value;
                        }
                        i++;
                    }
                }
            }
        }

    }
}
